import { Row, Col,Input, Button, Form, Flex, Space } from "antd";
import TextArea from "antd/es/input/TextArea";
import { FormInstance, useForm } from "antd/lib/form/Form";
import React, { useState } from "react"; 
import ReactJson from '@microlink/react-json-view'
 
    
import {CopyToClipboard} from 'react-copy-to-clipboard';

const JsonViewTool:React.FC = ()=>{

    const formRef = React.useRef<FormInstance>(null);
    const  [currentJson,setCurrentJson]  = useState<object>({})
    const  [inputJsonStr,setInputJsonStr]  = useState<string>('')
    const compress = ()=>{
        let json = formRef.current?.getFieldValue('currentJson')
        const miniJson = JSON.stringify(JSON.parse(json),null,0)
        formRef.current?.setFieldsValue({currentJson:miniJson}) 
        setInputJsonStr(miniJson)
    }
    const format = ()=>{
        let json = formRef.current?.getFieldValue('currentJson')
        const prettyJson = JSON.stringify(JSON.parse(json),null,4)
        formRef.current?.setFieldsValue({currentJson:prettyJson})
        setInputJsonStr(prettyJson)

    }

    const styels = {height:"60vh"}
    return <>
        <Form ref={formRef}>

         <Flex style={{marginBottom: '20px'}} align="center" justify="flex-start" vertical={false}>
                <Space>
                     <Button    onClick={format} >格式化</Button>
                    <Button onClick={compress} >压缩</Button>

                    <CopyToClipboard text={''+inputJsonStr}>
                                            <Button>复制</Button>
                                        </CopyToClipboard>
                </Space>
                  
                </Flex>
        <Row gutter={10} >

            <Col span={10}>
                <Form.Item label="输入" name="currentJson">
                <TextArea  onBlur={()=>{
                    let json = formRef.current?.getFieldValue('currentJson')
                    setCurrentJson(JSON.parse(json))
                }} style={styels} />
                </Form.Item>
            </Col>
           
            <Col span={10}>
                <ReactJson enableClipboard={(selectJsonObject:{src:Object})=>{
 
                    let result = JSON.stringify(selectJsonObject.src, null, 4)
                    formRef.current?.setFieldsValue({currentJson:result})
                    
                }} src={currentJson} />
            </Col>
            </Row>
        </Form>
    </>
}
export default JsonViewTool;